import { http, delay, HttpResponse } from "msw";
import { fakerZH_CN as faker } from "@faker-js/faker";

import { UserApi } from "@/service/login";
import { USER_LIST } from "../assets";

const signInUrl = import.meta.env.VITE_APP_BASEURL + UserApi.SignIn;
const userListUrl = import.meta.env.VITE_APP_BASEURL + UserApi.User;

//登录
const signIn = http.post(signInUrl, async ({ request }) => {
  const { username, password } = await request.json();
  const user = USER_LIST.find(item => item.username === username);

  if (!user || user.password !== password) {
    return HttpResponse.json({
      status: 10001,
      message: "Incorrect username or password.",
    });
  }

  //返回用户信息
  return HttpResponse.json({
    status: 0,
    message: "success",
    data: {
      user,
      accessToken: faker.string.uuid(),
      refreshToken: faker.string.uuid(),
    },
  });
});

//用户列表
const userList = http.get(userListUrl, async () => {
  await delay(1000); //延迟到达，默认100-400毫秒
  return HttpResponse.json({
    status: 0,
    message: "success",
    data: new Array(10).fill(0).map(() => ({
      fullname: faker.person.fullName(),
      email: faker.internet.email(),
      avatar: faker.image.avatar(),
      address: faker.location.streetAddress(),
    })),
  });
});
export default [signIn, userList];
